import React from 'react';
import Taro from '@tarojs/taro';
import {View, Image, Button, ScrollView} from '@tarojs/components';
import {connect} from 'react-redux';
import {AtBadge} from 'taro-ui';
import * as T from './types';
import actions from './actions';
import {store2Props} from './selectors';

import {
  OSS_BASE_PATH_PREFIX,
  OSS_PATH_PREFIX,
  SYNTHETCI_SEELCT_IP_STORE,
  GAME_TIMES_ONCE,
  GAME_TIMES_MORE,
  CODE_SUCCESS,
  IMAGE_EMPTY,
  GAME_STORAGE_INFO,
  GAME_SHARE_TITLE,
  GAME_RPICE_TYPE,
  PRIZE_RESULT_TYPE,
} from './constant';
import MemberModal from './components/MemberModal/MemberModal';

import 'taro-ui/dist/style/components/badge.scss';
import './index.less';
import MessageModal from './components/MessageModal/MessageModal';
import SyntheticPrizeModal from './components/SyntheticPrizeModal/SyntheticPrizeModal';
import PageLoading from '../../common/PageLoading';

actions().actions.loadReducer();

// @ts-ignore
@connect<Partial<T.IProps>, any>(store2Props, actions)
export default class SyntheticCardPa extends React.Component<Partial<T.IProps>, any> {
  // 使用state值
  constructor(props) {
    super(props);
    this.state = {
      query: {}, // 路径中携带参数
      pics: {
        prizeDarkBj: OSS_PATH_PREFIX + '/giftDisable.png', // 待点亮背景
        prizeLightBj: OSS_PATH_PREFIX + '/giftLight.png', // 已点亮背景
        syntheticIcon: OSS_PATH_PREFIX + '/collect.png', // 合成图标
        syntheticDisableIcon: OSS_PATH_PREFIX + '/synethicDisable.jpg', // 合成禁止图标
        cardBj: OSS_PATH_PREFIX + '/cardBj.png', // 卡背景
        buttonBj: OSS_PATH_PREFIX + '/buttonBj.png', // 按钮背景
        changeIcon: OSS_PATH_PREFIX + '/changeIcon.png', // 按钮背景
        gameShareIcon: OSS_BASE_PATH_PREFIX + '/gameShareIcon.png', // 分享至朋友圈
        gameShareThum: OSS_BASE_PATH_PREFIX + '/gameShareThum.png', // 分享缩略图
      },
      OPEARTE: [
        {
          label: '立即抽卡',
          count: 1,
          func: '',
          className: 'onceDrawButton',
        },
        {
          label: '十连抽',
          count: 10,
          func: '',
          className: 'continuousDrawButton',
        },
      ],

      // 角标配置
      badge: {
        max: 100000,
      },

      // 合成动画
      syntheticAnimation: {
        //动画效果
        animation: Taro.createAnimation({
          duration: 1000,
          timingFunction: 'linear',
          delay: 0,
        }),
        rodateNum: 0, // 旋转角度
        timer: null, //定时器,
      },

      // 合成提示语
      syntheticLabel: '',

      // 提示语模态框
      modal: {
        type: '',
        visible: false,
        message: '',
        extraMessage: '',
      },
      imageError: {}, // 错误图片
    };
  }

  componentDidShow() {
    this.handleGetRouterParams(); // 获取路由参数
    this.props.actions.init();
  }

  componentWillUnmount() {
    this.props.actions.clean();
  }

  componentWillReceiveProps(nextProps: Readonly<Partial<T.IProps>>, nextContext: any): void {
    // 合成结束
    if (nextProps.main.status.syntheticing == false && this.props.main.status.syntheticing == true) {
      this.handleClearSyntheticAnimation(); // 清除动画
      this.handleSetSyntheticLabel(nextProps.main.cardItems);

      // 成功则获取
      if (nextProps.main.response.synthetic == CODE_SUCCESS) {
        // 弹获取框，为了领取商品
        if (nextProps.main.syntheticResult) {
          this.handleModalShowAndHide('syntheic', true);
        }

        this.handleGameAvailableTimes(); // 获取游戏次数
        this.handleQueryAppallationItems(this.state.query.id);
        this.handleCardItemsByIp(this.state.query.id);
      } else {
        if (nextProps.main.codeMessage) {
          Taro.showToast({
            title: nextProps.main.codeMessage,
            icon: 'none',
            duration: 2000,
          });
        }
      }
    } else if (nextProps.main.status.loadingCard == false && this.props.main.status.loadingCard == true) {
      this.handleSetSyntheticLabel(nextProps.main.cardItems);
    }
  }

  /**
   * 获取路由参数
   */
  handleGetRouterParams = () => {
    let params = Taro.getCurrentInstance()?.router?.params;

    // 收藏进来的就直接去首页
    if (params.favorite) {
      Taro.redirectTo({
        url: '/pages/package-I/home/index',
      });
      return;
    }

    //重置参数就回到上一页
    if (params.reset) {
      Taro.navigateBack();
      return;
    }

    this.handleQuery();

    // 没有值判断缓存里是否有值
    if (!params.id) {
      let selectIpStorage = Taro.getStorageSync(SYNTHETCI_SEELCT_IP_STORE);
      console.log('index.tsx getselectIpStorage', selectIpStorage);
      if (selectIpStorage) {
        params.id = selectIpStorage.ipId;
        params.name = selectIpStorage.ipName;
      }
    }

    this.setState({
      query: params,
    });
    console.log('syntheticCard params', params);

    if (params && params.id) {
      this.handleCardItemsByIp(params.id); // 查询卡片列表
      this.handleQueryAppallationItems(params.id); // 查询称号商品列表
    }
  };

  /**
   * 查询信息
   */
  handleQuery = () => {
    this.handleQueryUserInfo(); // 目前从缓存里取
    this.handleQueryGameInfo();
  };

  /**
   * 查询当日游戏
   */
  handleQueryDailyGameTimes = () => {
    this.props.actions.action.loadGameDailyTimes();
  };

  /**
   * 查询游戏信息
   */
  handleQueryGameInfo = () => {
    this.props.actions.action.gamePlayingStatus({});
  };

  /**
   * 查询用户信息
   */
  handleQueryUserInfo = () => {
    let params = {};
    this.props.actions.action.loadUserInfo(params);
  };

  /**
   * 获取用户可用游戏次数限制
   */
  handleGameAvailableTimes = () => {
    console.log('index.tsx synthetciCard handleGameAvailableTimes');
    let params = {};
    this.props.actions.action.loadGameTimes(params);
  };

  /**
   * 查询礼品信息
   */
  handleQueryAppallationItems(id) {
    let params = {
      ipId: id,
    };
    this.props.actions.action.loadAppellationItems(params);
  }

  /**
   * 根据ip查询卡片信息
   */
  handleCardItemsByIp(id) {
    console.log('index.tsx handleCardItemsById id', id);
    let params = {
      ipId: id,
    };
    console.log('index.tsx handleCardItemsByIp parmas', params);
    this.props.actions.action.loadCardItems(params);
  }

  /**
   * 卡片个数决定提示语
   */
  handleSetSyntheticLabel = (items) => {
    let {
      main: {appellationItems},
    } = this.props;
    let disable = this.handleGetSyntheticStatus(appellationItems, items);
    this.setState({
      syntheticLabel: !disable ? '点击合成' : '等待合成',
    });
  };

  /**
   * 获取等待合成的状态（不可合成和等待合成）
   * @param appellationItems
   * @param items
   * @returns
   */
  handleGetSyntheticStatus = (appellationItems, items) => {
    let exsitEmpty = appellationItems.findIndex((i) => i.type == 'empty');
    let exsitFlag = exsitEmpty > -1 ? true : false;
    let prizeFlag = false;
    if (!exsitFlag) {
      prizeFlag = this.handlePrizeItemsGet(appellationItems);
    }
    let cardflag = false;
    if (!prizeFlag) {
      cardflag = this.handleSyntheticCardCount(items);
    }
    let disable = exsitFlag || prizeFlag || cardflag; // 判断是否具备合成条件

    return disable;
  };

  /**
   * 渲染
   * @returns
   */
  render() {
    if (!this.props.main) return null;
    let {
      main: {
        isLoading,
        appellationItems,
        cardItems,
        status: {loadingAppellation, loadingCard},
      },
    } = this.props;

    console.log('syntheticCard render this.props', this.props);

    return (
      <View className="pageSyntheticCardPa" catchMove>
        {this.renderTitleContent()}
        {this.renderPrizesContent(appellationItems)}
        {this.renderSyntheticContent()}
        {this.renderCardContent(cardItems)}
        {this.renderGameTimes()}
        {this.renderOperatesContent()}
        {this.renderMessageModal()}
        {this.renderMemberModal()}
        {this.renderSyntheticPrizeModal()}
      </View>
    );
  }

  /**
   * 渲染标题内容
   */
  renderTitleContent() {
    const {pics, query} = this.state;

    return (
      <View className="title">
        <View className="extra">
          <View className="extraTitle">您已选择:</View>
          <View className="extraSelectLabel">{query.name}</View>
        </View>
        <View className="changeIp" onClick={this.handleChangeIpConfirmModal}>
          <View className="label">切换IP</View>
          <Image src={pics.changeIcon} className="changeIcon" />
        </View>
      </View>
    );
  }

  /**
   * 渲染加载内容
   * @returns
   */
  renderLoadingContent() {
    return (
      <View className="loadingContent">
        <PageLoading />
      </View>
    );
  }

  /**
   * 渲染游戏次数
   */
  renderGameTimes() {
    const {
      main: {userInfo},
    } = this.props;
    return <View className="gameTimes">剩余游戏次数:{userInfo.gameAvailableTimes}</View>;
  }

  /**
   * 切换ip
   */
  handleChangeIpConfirmModal = () => {
    // 打开模态框
    this.handleMessageModalShowOrHide(true);
  };

  /**
   * 打开/关闭消息模态框
   */
  handleMessageModalShowOrHide = (visible) => {
    const {query} = this.state;

    this.setState({
      modal: {
        ...this.state.modal,
        visible,
        message: `您当前选择的IP为:${query.name}系列`,
        extraMessage: '确认切换吗？',
      },
    });
  };

  /**
   * 渲染奖品内容
   */
  renderPrizesContent(prizes) {
    console.log('index.tsx renderPrizesContent prizes', prizes);

    const {badge} = this.state;

    return (
      <View>
        <View className="prizeLabel">奖品展示</View>
        <View className="prizeContent">
          <ScrollView className="prizes" scrollX>
            <View className="content">
              {prizes.map((i: any, index: number) =>
                i.prizeType == GAME_RPICE_TYPE['product'] && i.remainingNum >= 0 ? (
                  <AtBadge key={'AtBadge' + index} value={i.remainingNum} className="item" maxValue={badge.max}>
                    {this.renderPrizeItems(index, i)}
                  </AtBadge>
                ) : (
                  <View className="item" key={'prize' + index}>
                    {this.renderPrizeItems(index, i)}
                  </View>
                ),
              )}
            </View>
          </ScrollView>
        </View>
      </View>
    );
  }

  /**
   * 渲染称号
   * @param index
   * @param i
   * @returns
   */
  renderPrizeItems(index, i) {
    return (
      <>
        <View
          className="thumInfo"
          style={
            i.obtainFlag
              ? {}
              : {
                  backgroundColor: '#000',
                  opacity: 0.5,
                }
          }
        >
          <Image
            src={this.getPrizeImage(i)}
            className="pImage"
            mode="aspectFit"
            onError={(e) =>
              this.handleImageError(e, index, {
                propName: 'appellationItems',
                imageState: 'imgUrl',
              })
            }
          />
        </View>
        <View className="prizeTitle">{i.prizeName}</View>
        {i.obtainFlag ? <></> : <View className="prizeExtraTitle">待点亮</View>}
      </>
    );
  }

  /**
   * 处理称号图片 (特殊处理道具和优惠券)
   * @param i
   * @returns
   */
  getPrizeImage = (i) => {
    let imageUrl = PRIZE_RESULT_TYPE[i.prizeType]?.thum || IMAGE_EMPTY;
    if (i.prizeType == GAME_RPICE_TYPE['card'] || i.prizeType == GAME_RPICE_TYPE['product']) {
      imageUrl = i.imgUrl || IMAGE_EMPTY;
    }
    return imageUrl;
  };

  /**
   * 渲染卡片
   * @param items
   * @returns
   */
  renderCardContent(items) {
    const {badge} = this.state;

    return (
      <ScrollView className="cards" scrollX>
        <View className="content">
          {items.map((i: any, index: number) => (
            <View className="item" key={'card' + index}>
              {i.cardNum > 0 ? (
                <AtBadge value={i.cardNum} maxValue={badge.max}>
                  <View className="cThumInfo">
                    <Image
                      src={i.imgUrl}
                      className="cardImage"
                      mode="scaleToFill"
                      onError={(e) =>
                        this.handleImageError(e, index, {
                          propName: 'cardItems',
                          imageState: 'imgUrl',
                        })
                      }
                    />
                    <View className="cExtraLabel">已获得</View>
                  </View>
                </AtBadge>
              ) : (
                <View className="cThumInfo">
                  <Image
                    style={{backgroundColor: '#000', opacity: 0.2}}
                    src={i.imgUrl || IMAGE_EMPTY}
                    className="cardImage"
                    mode="scaleToFill"
                    onError={(e) =>
                      this.handleImageError(e, index, {
                        propName: 'cardItems',
                        imageState: 'imgUrl',
                      })
                    }
                  />
                  <View className="cExtraLabel">未获得</View>
                </View>
              )}
            </View>
          ))}
        </View>
      </ScrollView>
    );
  }

  /**
   * 图片加载错误
   * @param e
   * @param index
   */
  handleImageError = (e, index, item) => {
    const {main} = this.props;
    const {propName, imageState} = item;
    let {imageError} = this.state;
    if (imageError[propName]) {
      imageError[propName] = imageError[propName].concat([index]);
    } else {
      imageError[propName] = [index];
    }
    let result = JSON.parse(JSON.stringify(main[propName]));
    let currentImage = imageError[propName];
    let ids = currentImage;
    ids.map((i) => {
      result[i] = {
        ...result[i],
        [imageState]: IMAGE_EMPTY,
      };
    });
    this.props.actions.action.commonChange('main.' + propName, result);
  };

  /**
   * 渲染合成图标
   * @returns
   */
  renderSyntheticContent() {
    const {
      pics,
      syntheticAnimation: {animation},
      syntheticLabel,
    } = this.state;

    let {
      main: {appellationItems, cardItems},
    } = this.props;

    let disable = this.handleGetSyntheticStatus(appellationItems, cardItems);
    console.log('renderSyntheticContent disable', disable);

    return (
      <View className="syntheticIcon" onClick={this.handleSynthetic}>
        <View animation={animation} className={disable ? 'thum_disable' : 'thum'}></View>
        <View className="syntheticLabel">{syntheticLabel}</View>
      </View>
    );
  }

  /**
   * 点击合成
   */
  handleSynthetic = () => {
    console.log('index.tsx handleSynthetic 点击合成');

    let {
      syntheticAnimation: {animation, rodateNum, timer},
      query,
    } = this.state;

    let {
      main: {cardItems, appellationItems, userInfo},
    } = this.props;
    console.log('index.tsx handlesynthetic items', cardItems);

    // 未具备合成条件
    let disable = this.handleGetSyntheticStatus(appellationItems, cardItems);
    if (disable) {
      return;
    }

    // 编辑参数
    if (query && query.id) {
      let params = {
        ipId: query.id,
      };
      this.props.actions.action.syntheticCard(params); // 调用后台合成接口
      timer = setInterval(() => {
        rodateNum = rodateNum + 30;
        animation.rotate(rodateNum).step();
        this.setState({
          syntheticAnimation: {
            rodateNum,
            animation: animation.export(),
            timer,
          },
          syntheticLabel: '',
        });
      }, 50);
    }
  };

  /**
   * 判断奖品是否全部开完毕
   */
  handlePrizeItemsGet = (items) => {
    let flag = true;
    for (let i = 0; i < items.length; i++) {
      if (!items[i].obtainFlag) {
        flag = false;
        break;
      }
    }

    return flag;
  };

  /**
   * 判断是否有条件合卡
   */
  handleSyntheticCardCount = (items) => {
    let flag = false;
    for (let i = 0; i < items.length; i++) {
      // 代表未集成卡
      if (items[i].cardNum == 0 || items[i].cardNum == null) {
        flag = true;
        break;
      }
    }

    if (items.length == 0) {
      flag = true;
    }

    return flag;
  };

  /**
   * 清除合成定时器
   */
  handleClearSyntheticAnimation() {
    console.log('清除定时器');
    let {
      syntheticAnimation: {timer, animation},
    } = this.state;

    // 清除定时器
    clearInterval(timer);

    this.setState({
      syntheticAnimation: {
        ...this.state.syntheticAnimation,
        animation: Taro.createAnimation({
          duration: 1000,
          timingFunction: 'linear',
          delay: 0,
        }),
        label: '等待合成',
      },
    });
  }

  /**
   * 渲染操作按钮
   */
  renderOperatesContent() {
    const {OPEARTE} = this.state;
    return (
      <View className="operates">
        {OPEARTE.map((i: any, index: number) => (
          <Button className={i.className} key={'operate' + index} onClick={() => this.handleOperates(i, index)}>
            {i.label}
          </Button>
        ))}
      </View>
    );
  }

  /**
   * 底部操作处理（立即抽卡和十连轴）
   */
  handleOperates = (item) => {
    const {query} = this.state;
    let {
      main: {userInfo, gameInfo, codeMessage},
    } = this.props;

    // 判断是否是会员
    if (!userInfo.accountType) {
      // 弹框显示非会员
      this.handleModalShowAndHide('member', true);
      return;
    }

    console.log('index.tsx handleOperate gameInfo', gameInfo);

    // 判断游戏是否可玩
    if (!gameInfo.isPlay) {
      Taro.showToast({
        title: '奖池升级中',
        icon: 'none',
        duration: 2000,
      });
      return;
    }

    if (!userInfo.gameAvailableTimes) {
      Taro.showToast({
        title: '做任务获取次数吧~',
        icon: 'none',
        duration: 2000,
      });

      return;
    }

    if (!userInfo.userDailyTimes) {
      Taro.showToast({
        title: '今日游戏次数已达上限~',
        icon: 'none',
        duration: 2000,
      });
      return;
    }

    // 十连抽处理
    if (item.count == GAME_TIMES_MORE) {
      if (userInfo.gameAvailableTimes < GAME_TIMES_MORE) {
        Taro.showToast({
          title: '做任务获取次数吧~',
          icon: 'none',
          duration: 2000,
        });

        return;
      }
      if (userInfo.userDailyTimes == 0) {
        Taro.showToast({
          title: '今日游戏次数已达上限~',
          icon: 'none',
          duration: 2000,
        });
        return;
      } else if (userInfo.userDailyTimes > 0 && userInfo.userDailyTimes < GAME_TIMES_MORE) {
        Taro.showToast({
          title: '今日游戏次数已不足10次~',
          icon: 'none',
          duration: 2000,
        });
        return;
      }
    }

    let url = '/pages/package-I/syntheticDrawCard/index?id=' + query.id + '&count=' + item.count;
    Taro.navigateTo({
      url,
    });
  };

  /**
   * 渲染提示模态框
   */
  renderMessageModal() {
    const {modal} = this.state;

    return (
      <MessageModal
        modal={modal}
        onCancel={() => this.handleMessageModalShowOrHide(false)}
        onSubmit={this.handleChangeIp}
      />
    );
  }

  /**
   * 确认切换
   */
  handleChangeIp = () => {
    // 关闭模态框
    const {query} = this.state;

    let url = '/pages/package-I/syntheticCardIp/index?id=' + this.state.query.id;
    // 如果有任务的话
    if (query && query.taskId && query.taskConditionsType) {
      url = url + '&taskId=' + query.taskId + '&taskConditionsType=' + query.taskConditionsType;
    }
    this.handleMessageModalShowOrHide(false);
    // Taro.navigateTo({
    //   url,
    // });
    Taro.navigateBack();
  };

  /**
   * 渲染会员弹框
   */
  renderMemberModal() {
    const {
      modal: {visible, type},
    } = this.state;

    return (
      <MemberModal
        visible={visible && type == 'member'}
        onCancel={() => this.handleModalShowAndHide('', false)}
        onActivate={() => this.handleActivateMember()}
      />
    );
  }

  /**
   * 模态框的弹出和隐藏
   */
  handleModalShowAndHide = (type, visible, item = null) => {
    console.log('index.tsx handleModalShowAndHide type', type, 'visible', visible);

    this.setState({
      modal: {
        ...this.state.modal,
        type: visible ? type : '',
        visible,
        item,
      },
    });
  };

  /**
   * 渲染礼品模态框
   */
  renderSyntheticPrizeModal() {
    const {
      modal: {visible, type},
    } = this.state;

    return (
      <SyntheticPrizeModal
        visible={visible && type == 'syntheic'}
        onCancel={() => this.handleModalShowAndHide('', false)}
      />
    );
  }

  /**
   * 确定开通会员
   */
  handleActivateMember = () => {
    this.handleModalShowAndHide('', false); // 关闭模态框
    // 跳转到开通会员界面
    Taro.redirectTo({
      url: '/pages/package-A/memberOpen/index',
    });
  };

  /**
   * 收藏
   * @param res
   * @returns
   */
  onAddToFavorites(res) {
    const {
      pics: {gameShareIcon},
    } = this.state;

    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target);
    }
    console.log('选择iponShareAppMessage res.target', res.target);
    return {
      title: GAME_SHARE_TITLE,
      imageUrl: gameShareIcon,
      query: 'favorite=true',
    };
  }
}
